/**
 * 统一Hooks库
 * @description 整合所有自定义hooks，提供统一的导入入口
 * @author AI Assistant
 * @date 2025-08-18
 */

import { ref, computed, onMounted } from 'vue'
import { SimpleStorage, memoryManager } from '@/utils'

// ================================
// API相关Hooks
// ================================

/**
 * 通用API Hook - 简化单页面使用
 * @param apiFn API函数
 * @returns API状态和执行函数
 */
export function useApi<T = any>(apiFn: (...args: any[]) => Promise<T>) {
    const data = ref<T | null>(null)
    const loading = ref(false)
    const error = ref<Error | null>(null)

    const execute = async (...args: any[]) => {
        loading.value = true
        error.value = null

        try {
            const result = await apiFn(...args)
            data.value = result
            return result
        } catch (err) {
            error.value = err as Error
            throw err
        } finally {
            loading.value = false
        }
    }

    return {
        data: computed(() => data.value),
        loading: computed(() => loading.value),
        error: computed(() => error.value),
        execute
    }
}

/**
 * 自动执行的API Hook
 * @param apiFn API函数
 * @param params 参数
 * @param options 选项
 * @returns API状态和执行函数
 */
export function useAutoApi<T = any>(
    apiFn: (...args: any[]) => Promise<T>,
    params: any[] = [],
    options: { immediate?: boolean } = { immediate: true }
) {
    const { data, loading, error, execute } = useApi(apiFn)

    if (options.immediate) {
        execute(...params)
    }

    const refresh = () => execute(...params)

    return {
        data,
        loading,
        error,
        execute,
        refresh
    }
}

/**
 * 带缓存的API Hook
 * @param key 缓存键
 * @param apiFn API函数
 * @param cacheTime 缓存时间(秒)
 * @returns API状态和执行函数
 */
export function useCachedApi<T = any>(key: string, apiFn: (...args: any[]) => Promise<T>, cacheTime = 300) {
    const { data, loading, error, execute } = useApi(async (...args: any[]) => {
        const cacheKey = `${key}_${JSON.stringify(args)}`

        // 检查缓存
        const cached = memoryManager.get(cacheKey)
        if (cached) {
            return cached
        }

        // 执行API
        const result = await apiFn(...args)

        // 保存缓存
        memoryManager.set(cacheKey, result, cacheTime * 1000)

        return result
    })

    const clearCache = () => memoryManager.clear()

    return {
        data,
        loading,
        error,
        execute,
        clearCache
    }
}

/**
 * 表单提交Hook
 * @param apiFn API函数
 * @param options 选项
 * @returns 提交状态和函数
 */
export function useSubmitApi<T = any>(
    apiFn: (data: any) => Promise<T>,
    options: {
        onSuccess?: (result: T) => void
        onError?: (error: Error) => void
        showToast?: boolean
    } = {}
) {
    const { showToast = true } = options
    const { data, loading, error, execute } = useApi(apiFn)

    const submit = async (formData: any) => {
        try {
            const result = await execute(formData)

            if (showToast) {
                uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                })
            }

            options.onSuccess?.(result)
            return result
        } catch (err) {
            if (showToast) {
                uni.showToast({
                    title: '提交失败',
                    icon: 'none'
                })
            }

            options.onError?.(err as Error)
            throw err
        }
    }

    return {
        data,
        loading,
        error,
        submit
    }
}

// ================================
// 存储相关Hooks
// ================================

/**
 * 本地存储Hook
 * @param key 存储键
 * @param defaultValue 默认值
 * @returns 存储值和设置函数
 */
export function useStorage<T>(key: string, defaultValue: T) {
    const storedValue = SimpleStorage.get(key)
    const data = ref<T>(storedValue !== null ? storedValue : defaultValue)

    const setValue = (value: T) => {
        data.value = value
        SimpleStorage.set(key, value)
    }

    const removeValue = () => {
        data.value = defaultValue
        SimpleStorage.remove(key)
    }

    return {
        value: computed(() => data.value),
        setValue,
        removeValue
    }
}

/**
 * 内存缓存Hook
 * @param key 缓存键
 * @param ttl 过期时间(ms)
 * @returns 缓存值和设置函数
 */
export function useMemoryCache<T>(key: string, ttl = 3600000) {
    const data = ref<T | null>(memoryManager.get(key))

    const setValue = (value: T) => {
        data.value = value
        memoryManager.set(key, value, ttl)
    }

    const removeValue = () => {
        data.value = null
        memoryManager.delete(key)
    }

    const refresh = () => {
        data.value = memoryManager.get(key)
    }

    return {
        value: computed(() => data.value),
        setValue,
        removeValue,
        refresh
    }
}

/**
 * 通用缓存Hook (useCache 别名)
 * @param key 缓存键
 * @param ttl 过期时间(ms)
 * @returns 缓存值和设置函数
 */
export const useCache = useMemoryCache

// ================================
// 性能相关Hooks
// ================================

/**
 * 简化的性能监控Hook
 * @param options 监控选项
 * @returns 性能指标和控制函数
 */
export function usePerformance(
    _options: {
        enableFPSMonitor?: boolean
        enableMemoryMonitor?: boolean
        reportInterval?: number
    } = {}
) {
    const metrics = ref({
        fps: 60,
        memory: 0,
        loadTime: 0,
        renderTime: 0
    })

    const isMonitoring = ref(false)

    // 开始监控
    const startMonitoring = () => {
        if (isMonitoring.value) return
        isMonitoring.value = true
        console.log('性能监控已开始')
    }

    // 停止监控
    const stopMonitoring = () => {
        isMonitoring.value = false
        console.log('性能监控已停止')
    }

    return {
        metrics: computed(() => metrics.value),
        isMonitoring: computed(() => isMonitoring.value),
        startMonitoring,
        stopMonitoring
    }
}

/**
 * 简化的页面性能Hook
 * @returns 页面性能指标
 */
export function usePagePerformance() {
    const pageLoadTime = ref(0)
    const firstPaintTime = ref(0)
    const firstContentfulPaintTime = ref(0)

    onMounted(() => {
        // 简化的性能测量
        pageLoadTime.value = Date.now()
        firstPaintTime.value = 100
        firstContentfulPaintTime.value = 200
    })

    return {
        pageLoadTime: computed(() => pageLoadTime.value),
        firstPaintTime: computed(() => firstPaintTime.value),
        firstContentfulPaintTime: computed(() => firstContentfulPaintTime.value)
    }
}

// ================================
// 懒加载相关Hooks (简化版)
// ================================

/**
 * 简化的懒加载组件Hook
 * @returns 懒加载状态
 */
export function useLazyComponent() {
    const isVisible = ref(true)
    const isLoaded = ref(true)
    const elementRef = ref()

    return {
        isVisible,
        isLoaded,
        elementRef
    }
}

/**
 * 简化的懒加载图片Hook
 * @param src 图片地址
 * @returns 图片加载状态
 */
export function useLazyImage(src: string) {
    const currentSrc = ref(src)
    const loading = ref(false)
    const error = ref(false)
    const isVisible = ref(true)
    const elementRef = ref()

    return {
        currentSrc,
        loading,
        error,
        isVisible,
        elementRef
    }
}
